package com.genius.aspect;

import com.genius.annotation.GraceTransaction;
import com.genius.utils.TransactionUtils;
import io.seata.core.exception.TransactionException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@Aspect
public class GraceTransactionAspect {

    /**
     * 调用service前，手动创建或加入全局事务
     */
    @Before(value = "@annotation(graceTransaction)")
    public void beginTransaction(GraceTransaction graceTransaction) {
        log.info("手动开启全局事务");
        // 手动开启全局事务
        TransactionUtils.beginGlobalTransaction();
    }

    /**
     * 捕获异常，则手动回滚全局事务
     * @param throwable 异常
     * @throws TransactionException 事务异常
     */
    @AfterThrowing(value = "@annotation(graceTransaction)", throwing = "throwable")
    public void rollback(GraceTransaction graceTransaction, Throwable throwable) throws TransactionException {

        log.info("捕获异常信息，事务回滚，异常信息为{}" + throwable.getMessage());
        TransactionUtils.rollbackGlobalTransaction();
    }

}
